<script setup lang="ts">
import type { ElectricityInfo, EquipmentInfoV2Vo, EquipmentVo } from './type'

import { computed, onBeforeMount, onMounted, onUnmounted, ref, shallowRef, unref } from 'vue'
import { indicatorApi, productionApi, sysDictionaryEncoApi } from '~/api'
import DashboardHeader from '~/components/DashboardHeader/index.vue'
import ItemFive from './components/item-five.vue'
import ItemFour from './components/item-four.vue'
import ItemOne from './components/item-one.vue'
import ItemServen from './components/item-serven.vue'
import ItemSix from './components/item-six.vue'
import ItemThree from './components/item-three.vue'
import ItemTwo from './components/item-two.vue'

defineOptions({ name: 'EnergyDashboard' })

const show = ref(false)

const electricityInfo = shallowRef<Nullable<ElectricityInfo>>({
  electricityDay: null,
  power: null,
  electricityYear: null,
  electricityMonth: null,
  electricityMonthYoy: null,
  vub: null,
  cub: null,
  electricityF: null,
  electricityP: null,
  electricityG: null,
})

const equipmentInfo = shallowRef<Nullable<EquipmentInfoV2Vo>>({
  equipmentTotal: null,
  equipmentRunNum: null,
  typeList: null,
})

const itemTwoData1 = computed(() => {
  if (electricityInfo.value.electricityMonth === null) {
    return []
  }
  return electricityInfo.value.electricityMonth.map((v) => {
    return {
      name: v.time,
      value: v.value,
    }
  })
})
const itemTwoData2 = computed(() => {
  if (electricityInfo.value.electricityMonthYoy === null) {
    return []
  }
  return electricityInfo.value.electricityMonthYoy.map((v) => {
    return {
      name: v.time,
      value: v.value,
    }
  })
})

const itemFourData1 = ref<{ title: string, value: any }>({
  title: '产量',
  value: 0,
})
const itemFourData2 = ref<{ title: string, value: any }>({
  title: '不合格率',
  value: 0,
})

const itemFiveData1 = computed(() => {
  if (electricityInfo.value.vub === null) {
    return []
  }
  return electricityInfo.value.vub.map((v) => {
    return {
      name: v.time,
      value: v.value,
    }
  })
})

const itemFiveData2 = computed(() => {
  if (electricityInfo.value.cub === null) {
    return []
  }
  return electricityInfo.value.cub.map((v) => {
    return {
      name: v.time,
      value: v.value,
    }
  })
})

const itemSixData = computed(() => {
  const e = unref(electricityInfo)
  const sum = (e.electricityF ?? 0) + (e.electricityP ?? 0) + (e.electricityG ?? 0)
  const t1 = divide(e.electricityF, sum)
  const t2 = divide(e.electricityP, sum)
  const t3 = e.electricityG === null ? '--' : (e.electricityG === 0 || sum === 0) ? '0.00' : calculateC(t1, t2)
  const isNotEmpty = (v: any) => v ! == null && v !== undefined && v !== ''
  return [
    { name: '峰时段', value1: `${e.electricityF ?? '--'}`, value2: t1 !== '--' ? `${t1}%` : t1, content: +t1 > 20 && isNotEmpty(e.electricityF) ? '只进行必须操作,安排非生产活动' : '无需优化' },
    { name: '平时段', value1: `${e.electricityP ?? '--'}`, value2: t2 !== '--' ? `${t2}%` : t2, content: +t2 > 50 && isNotEmpty(e.electricityP) ? '确保在平段结束时，高耗能设备能按计划停止或转入低耗能状态' : '无需优化' },
    { name: '谷时段', value1: `${e.electricityG ?? '--'}`, value2: t3 !== '--' ? `${t3}%` : t3, content: +t3 < 30 && isNotEmpty(e.electricityG) ? '调整班次（如增加夜班或三班倒），将主要生产活动集中在谷时段和平段' : '无需优化' },
  ]
})

const equipmentRatio = computed(() => {
  if (equipmentInfo.value.equipmentTotal === null || equipmentInfo.value.equipmentRunNum === null) {
    return 0
  }
  if (equipmentInfo.value.equipmentTotal === 0) {
    return 0
  }
  return Math.round(equipmentInfo.value.equipmentRunNum / equipmentInfo.value.equipmentTotal * 100)
})

const itemServenData1 = computed<EquipmentVo[]>(() => {
  const list = (unref(equipmentInfo).typeList || []).find(item => item.key === '2')?.list ?? []
  const find = (str: string) => {
    return list.find(item => item.name.startsWith(str))
  }
  return [
    {
      name: 'A灯-6线LED装配机',
      number: '',
      value: null,
      status: find('A灯-6线')?.status ?? 0,
    },
    {
      name: 'A灯-7线LED装配机',
      number: '',
      value: null,
      status: find('A灯-7线')?.status ?? 0,
    },
    {
      name: 'G45-1线LED装配机',
      number: '',
      value: null,
      status: find('G45-1线')?.status ?? 0,
    },
    {
      name: 'C37-1线LED装配机',
      number: '',
      value: null,
      status: find('C37-1线')?.status ?? 0,
    },
    {
      name: 'P45-1线LED装配机',
      number: '',
      value: null,
      status: find('P45-1线')?.status ?? 0,
    },
  ]
})

const itemServenData2 = computed(() => {
  return (unref(equipmentInfo).typeList || []).find(item => item.key === '1')?.list ?? []
})

function divide(a: number | null, b: number | null, n: number = 2) {
  if (a === null || b === null)
    return '--'
  return b !== 0 ? (a * 100 / b).toFixed(n) : '0.00'
}

function calculateC(a: string | number, b: string | number) {
  a = a.toString()
  b = b.toString()
  return ((10000 - (Number.parseFloat(a) * 100) - (Number.parseFloat(b) * 100)) / 100).toFixed(2)
}

async function getElectricityInfo() {
  const res = await productionApi.getElectricityInfo()
  electricityInfo.value = res.data as ElectricityInfo
}

async function getEquipmentInfo() {
  const res = await productionApi.getEquipmentInfoV2()
  res.data = res.data ?? {
    equipmentTotal: 0,
    equipmentRunNum: 0,
    typeList: [],
  }
  equipmentInfo.value = res.data as EquipmentInfoV2Vo
}

async function getKanbanInfo() {
  const { data: dicts } = await sysDictionaryEncoApi.queryList('NENG_YUAN_SHENG_CHAN')
  const indicatorNumberOfCL = dicts.find(v => v.dicKey === 'CL')?.dicValue
  const indicatorNumberOfBHGL = dicts.find(v => v.dicKey === 'BHGL')?.dicValue
  if (indicatorNumberOfCL) {
    try {
      const { data } = await indicatorApi.getIndicatorNowValue('1y', indicatorNumberOfCL)
      itemFourData1.value = {
        title: `产量（${data.unit}）`,
        value: data.valStr,
      }
    }
    catch (error) {
      console.error(error)
    }
  }
  if (indicatorNumberOfBHGL) {
    try {
      const { data } = await indicatorApi.getIndicatorNowValue('0m', indicatorNumberOfBHGL)
      itemFourData2.value = {
        title: `不合格率（${data.unit}）`,
        value: data.valStr,
      }
    }
    catch (error) {
      console.error(error)
    }
  }
}

let timer: ReturnType<typeof setInterval>

onBeforeMount(() => {
  document.documentElement.classList.add('_transparent_bg_')

  getElectricityInfo()
  getKanbanInfo()
  getEquipmentInfo()
})
onUnmounted(() => {
  document.documentElement.classList.remove('_transparent_bg_')
  timer && clearInterval(timer)
})

onMounted(() => {
  show.value = true
  timer = setInterval(() => {
    getElectricityInfo()
    getEquipmentInfo()
    getKanbanInfo()
  }, 10e3)
})
</script>

<template>
  <div class="dashboard-wrapper h-full w-full overflow-auto">
    <div class="energy-dashboard dashboard relative h-full min-h-900px min-w-1600px w-full">
      <DashboardHeader class="absolute left-0 right-0 top-0 z-1" :show-time="false" :show-weather="false" :show-erp="false" :show-energy="false" :show-hr="false" />
      <div class="energy-dashboard h-full w-full flex flex-col gap-3 overflow-hidden p-3">
        <div class="mt-17 max-h-80 flex items-center gap-3">
          <Transition
            enter-active-class="animate__animated animate__fadeInDown"
            leave-active-class="animate__animated animate__fadeOutUp"
          >
            <ItemOne
              v-if="show" class="max-w-1/4 flex-1/4"
              :value1="electricityInfo.power ?? 0"
              :value2="electricityInfo.electricityDay ?? '--'"
            />
          </Transition>
          <Transition
            enter-active-class="animate__animated animate__fadeInDown animate__delay-1s"
            leave-active-class="animate__animated animate__fadeOutUp"
          >
            <ItemTwo
              v-if="show" class="max-w-1/4 flex-1/4"
              :total="electricityInfo.electricityYear ?? '--'"
              :data1="itemTwoData1" :data2="itemTwoData2"
            />
          </Transition>
          <Transition
            enter-active-class="animate__animated animate__fadeInDown animate__delay-2s"
            leave-active-class="animate__animated animate__fadeOutUp"
          >
            <ItemThree
              v-if="show" class="max-w-1/4 flex-1/4"
              :value1="equipmentRatio"
              :value2="equipmentInfo.equipmentTotal ?? '--'"
              :value3="equipmentInfo.equipmentRunNum ?? '--'"
            />
          </Transition>
          <Transition
            enter-active-class="animate__animated animate__fadeInDown animate__delay-3s"
            leave-active-class="animate__animated animate__fadeOutUp"
          >
            <ItemFour v-if="show" :data1="itemFourData1" :data2="itemFourData2" class="max-w-1/4 flex-1/4" />
          </Transition>
        </div>
        <div class="flex flex-auto gap-3 overflow-auto">
          <div class="max-w-1/4 flex flex-1/4 flex-col overflow-hidden">
            <Transition
              enter-active-class="animate__animated animate__fadeInLeft"
              leave-active-class="animate__animated animate__fadeOutLeft"
            >
              <ItemFive v-if="show" class="flex-1/2" :data1="itemFiveData1" :data2="itemFiveData2" />
            </Transition>
            <Transition
              enter-active-class="animate__animated animate__fadeInLeft animate__delay-1s"
              leave-active-class="animate__animated animate__fadeOutLeft"
            >
              <ItemSix v-if="show" class="flex-1/2" :data="itemSixData" />
            </Transition>
          </div>
          <div class="max-w-3/4 flex-auto overflow-hidden">
            <Transition
              enter-active-class="animate__animated animate__fadeInRight"
              leave-active-class="animate__animated animate__fadeOutRight"
            >
              <ItemServen
                v-if="show"
                :data1="itemServenData1"
                :data2="itemServenData2"
              />
            </Transition>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss">
.dashboard-wrapper {
  scrollbar-width: thin;
  .dashboard {
    background-color: rgb(6, 19, 42);
    background-image: url('~/assets/images/bg.webp');
    background-repeat: no-repeat;
    background-size: cover;
    background-position: center center;

    .block-body {
      background: rgba(31, 82, 145, 0.1);
    }
  }
}
.energy-dashboard {
  --animate-delay: 0.2s;
  .block-body {
    background: rgba(31, 82, 145, 0.1);
  }
}
</style>
